<?php
/**
 * Created by jinqiang on 2024/7/15 16:30.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Wechat;


use App\Http\Models\Mysql\SsyConfigTable;
use App\Http\Models\Mysql\SsyJyProductListTable;
use App\Http\Models\Mysql\SsyProcessingListDetailsTable;
use App\Http\Models\Mysql\SsyScanCodeUserLogTable;
use App\Http\Models\Mysql\SsyScanCodeUserTable;
use App\Http\Models\Mysql\SsyStyleImagesTable;
use App\Http\Repository\AntifakeRepository;

class AntifakeService
{
    public function getScheme()
    {
        $res = AntifakeRepository::getScheme('kz');
        if($res['openlink'] ?? ""){
            return ['code' => 0, 'data' => ['openlink' => $res['openlink']]];
        }
        return ['code' => -1, 'msg' => "获取链接失败", 'msg' => $res];
    }

    public function search($sub, $code)
    {
        $res = AntifakeRepository::jscode2session($sub, $code);
        $userObj = (new SsyScanCodeUserTable())->where('openid', $res['openid'] ?? "")->where('source', $sub == 'js' ? 2 : 1)->first();
        if(empty($userObj)){
            return ['code' => -1, 'msg' => '用户还没有授权', 'data' => $res['openid']];
        }
        return ['code' => 0, 'msg' => '用户已经授权过了', 'data' => $userObj->toArray()];
    }

    public function addUser($data)
    {
        $saveData = [
            'nickname' => $data['nickname'] ?: "微信用户",
            'avatarurl' => $data['avatarurl'],
            'openid' => $data['openid'],
            'sex' => $data['sex'] == 1 ? "男" : ($data['sex'] == 2 ? "女" : "其他"),
            'token' => md5($data['openid'].time()),
            'source' => $data['sub'] == 'js' ? 2 : 1,//1十三余 2锦瑟
            'createtime' => date('Y-m-d H:i:s')
        ];
        $res = (new SsyScanCodeUserTable())->createData($saveData);
        if($res['code'] === 0){
            return ['code' => 0, 'msg' => '授权成功', 'data' => $saveData];
        }
        return ['code' => -1, 'msg' => '授权失败', 'data' => $res];
    }

    public function getPhone($code)
    {
        $token = $_SERVER["HTTP_TOKEN"] ?? "";
        if(empty($token)){
            return ['code' => -1, 'msg' => "请先授权"];
        }
        $user = (new SsyScanCodeUserTable())->where('token', $token)->first();
        if(empty($user)){
            return ['code' => -1, 'msg' => "用户未授权"];
        }
        $sub = $user->source == 2 ? "js" : "kz";
        $res = AntifakeRepository::getPhoneNumber($sub, $code);
        if($res['errcode'] !== 0){
            AntifakeRepository::clearAccessToken($sub);
            $res = AntifakeRepository::getPhoneNumber($sub, $code);
        }
        if($res['errcode'] !== 0){
            return ['code' => -1, 'msg' => '授权用户手机失败', 'data' => $res];
        }
        //info("授权用户手机", [$res]);
        (new SsyScanCodeUserTable())->updateData($user->id, ['phone' => $res['phone_info']['phoneNumber']]);
        return ['code' => 0, 'msg' => "授权用户手机成功", 'data' => $res['phone_info']];
    }

    public function scancode($number, $deviceId)
    {
        $token = $_SERVER["HTTP_TOKEN"] ?? "";
        if(empty($token)){
            return ['code' => -1, 'msg' => "请先授权"];
        }
        $user = (new SsyScanCodeUserTable())->where('token', $token)->first();
        if(empty($user)){
            return ['code' => -1, 'msg' => "用户未授权"];
        }
        $detailObj = (new SsyProcessingListDetailsTable())->where('number', $number)->first();
        $jyProductObj = null;
        if(!empty($detailObj)){
            $subjects = array_column(config("scm.subject"), null, "is_subject");
            $sub = $user->source == 2 ? "js" : "kz";//kz 包括：SSY, SSYE
            $jyProductObj = (new SsyJyProductListTable())->where('product_code', $detailObj['sku_code'])
                //->where('brand_code', 'like', $subjects[$sub]['brand_code']."%")
                ->first();
        }
        if(empty($detailObj) || empty($jyProductObj)){
            $createTime = [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')];
            $errNum = (new SsyScanCodeUserLogTable())->where('uid', $user->id)->where('source', $user->source)->where('status', '>', 0)
                ->whereBetween('createtime', $createTime)->count();
            if($errNum >= 10){
                return ['code' => -1, 'msg' => "今日无效二维码扫描次数已达上限"];
            }
            $data = [
                'uid'=> $user->id,
                'nickname'=>$user->nickname,
                'avatarurl'=>$user->avatarurl ?? "",
                'number' => $number,
                'phone' => $user->phone ?? "",
                'deviceId' => $deviceId, //设备号
                'request_ip' => request()->getClientIp(),
                'status'=>1, //不是正确的二维码
                'source'=>$user->source,
                'createtime' => date('Y-m-d H:i:s'),
            ];
            (new SsyScanCodeUserLogTable())->createData($data);
            return ['code' => 2, 'msg' => "请扫码正确的二维码!"];
        }
        //图片
        $img = $jyProductObj->img ?? "";
        if(empty($img)){
            $imgObj = (new SsyStyleImagesTable())->where('type_no', $detailObj->type_no)->first();
            $img = $imgObj->images ?? "";
        }
        $skuId = $detailObj->batch ? $jyProductObj->type_no : $detailObj->sku_code;
        $typeName = $jyProductObj->product_name;
        //首次查询
        $logObj = (new SsyScanCodeUserLogTable())->where('number', $number)->orderBy('createtime', 'asc')->first(['createtime']);
        $firstTime = $logObj->createtime ?? date('Y-m-d H:i:s');
        //查询次数
        $totalNum = (new SsyScanCodeUserLogTable())->where('number', $number)->count();
        $data = [
            'uid'=> $user->id,
            'nickname'=>$user->nickname,
            'avatarurl'=>$user->avatarurl ?? "",
            'number' => $number,
            'phone' => $user->phone ?? "",
            'deviceId' => $deviceId, //设备号
            'request_ip' => request()->getClientIp(),
            'status' => 0,
            'source'=>$user->source,
            'createtime' => date('Y-m-d H:i:s'),
        ];
        (new SsyScanCodeUserLogTable())->createData($data);
        $logData = [
            'pic' => $img, 'sku_id' => $skuId, 'name' => $typeName, 'first_date' => $firstTime, 'delivery_time' => $detailObj->delivery_time, 'num' => $totalNum+1
        ];
        //info("扫码", [$logData]);
        return ['code' => 0, 'msg' => '扫码成功', 'data' => $logData];
    }
}
